import React, { useEffect, useState, useCallback } from 'react';
import { Modal, Form, Input, message } from 'antd';
import { Project } from '../../model/project';
import TextArea from 'antd/lib/input/TextArea';
import { FieldData } from 'rc-field-form/lib/interface';

interface formProps {
    visible: boolean,
    setVisible: Function,
    doFetch?: Function
}

export default function CreateForm(props: formProps) {
    const {visible, setVisible, doFetch} = props;
    const [form] = Form.useForm();
    const [project, setProject] = useState(new Project({name: '', description: ''}));

    const handleCancel = () => {
        setVisible(false);
    }

    const handleSubmit = () => {
        project.doCreate().then(res => {
            if(res.status === 200) {
                message.success('创建成功！');
                setVisible(false);
                if(doFetch) {
                    doFetch();
                }
            } else {
                message.success('创建失败！');
            }
            setProject(new Project({name: '', description: ''}));
        });
    }

    const handleChange = (changedFields: FieldData[], allFields: FieldData[]) => {
        const update = new Project(project);
        
        for(const change of changedFields) {
            if(Array.isArray(change.name)) {
                if(change.name[0] === 'name') {
                    update.name = change.value;
                }
    
                if(change.name[0] === 'description') {
                    update.description = change.value;
                }
            }
        }
        setProject(update);
    };

    return (
        <>
            <Modal title="新建项目" visible={visible} onOk={handleSubmit} onCancel={handleCancel}>
                <Form 
                    form={form}
                    style={{ width: '100%' }}
                    name="basic"
                    labelCol={{ span: 4 }}
                    initialValues={{ remember: true }}
                    onFieldsChange={handleChange}
                >
                    <Form.Item
                        label="项目名称"
                        name="name"
                        rules={[{ required: true, message: '请输入项目名称!' }]}
                    >
                        <Input name="name" autoComplete="off"/>
                    </Form.Item>

                    <Form.Item
                        label="描述"
                        name="description"
                        rules={[{ required: true, message: '请输入描述!' }]}
                    >
                        <TextArea name="description" autoComplete="off"/>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
}